package com.sita.linboard.login;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.sita.linboard.R;
import com.sita.linboard.base.ActivityCollector;
import com.sita.linboard.base.BaseActivity;
import com.sita.linboard.base.BaseApplication;
import com.sita.linboard.driverInfo.ClearBackBean;
import com.sita.linboard.http.RestClient;
import com.sita.linboard.utils.BitmapUtils;
import com.sita.linboard.utils.ConstantValues;
import com.sita.linboard.utils.LogUtils;
import com.sita.linboard.utils.SpUtils;
import com.sita.linboard.utils.ToastUtils;

import java.io.File;

import pl.aprilapps.easyphotopicker.DefaultCallback;
import pl.aprilapps.easyphotopicker.EasyImage;
import pl.tajchert.nammu.Nammu;
import pl.tajchert.nammu.PermissionCallback;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedFile;
import retrofit.mime.TypedString;

/**
 * Created by Jason on 2016/8/23.
 */
public class RegisterSecondActivity extends BaseActivity implements View.OnClickListener{
    private final int PHONE = 0;//相机获取
    private final int GALLERY = 1;//相册获取
    private ImageView vehicle_head,vehicle_end;
    private EditText user_name,user_gender,user_snNumber,user_snType;
    private Button confirm;
    private File headfile,endfile;
    private  RegisterSecondRequest request;
    private ImageView genderImg,snImg;
    private LinearLayout allBg_img;
    private boolean isAccountChanged;
    private Uri imageUri;
    private Bitmap bitmap;
    private PopupWindow popupWindow;
    private PopupWindow typePop;
    private static String driverPhone;
    private static boolean isShowPop = true;
    public enum AppState {
        FROM_LAUNCH,
        IN_FOREGROUND,
        IN_BACKGROUND,
        IN_CAMERA_PHOTO
    }
    @Override
    protected void initData() {
        ActivityCollector.addActivity(this);
        vehicle_end.setOnClickListener(this);
        vehicle_head.setOnClickListener(this);
        confirm.setOnClickListener(this);
        genderImg.setOnClickListener(this);
        snImg.setOnClickListener(this);

    }



    @Override
    protected void initView(Bundle savedInstanceState) {
        vehicle_head = bindView(R.id.vehicle_head_img);
        vehicle_end = bindView(R.id.vehicle_end_img);
        allBg_img = bindView(R.id.all_layout);
        confirm  =bindView(R.id.next_step_second);
        user_name = bindView(R.id.register_second_name);
        user_gender = bindView(R.id.register_second_sex);
        user_snType = bindView(R.id.register_second_sn);
        user_snNumber = bindView(R.id.register_second_sn_number);
        genderImg = bindView(R.id.gender_img);
        snImg = bindView(R.id.sn_img);

    }

    @Override
    protected int getId() {
        return R.layout.activity_registersecond;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.vehicle_head_img:
                if(Build.VERSION.SDK_INT>=23) {
                    String[] mPermissionList = new String[]{Manifest.permission.CAMERA};
                    ActivityCompat.requestPermissions(RegisterSecondActivity.this, mPermissionList, 123);
                }
                showPopWindow(PHONE);
                break;
            case R.id.vehicle_end_img:
                showPopWindow(GALLERY);
                break;
            case R.id.next_step_second:
                UploadData();
                break;
            case R.id.gender_img:
                showPop(genderImg);
                break;
            case R.id.sn_img:
                showTypePop(snImg);
                break;
        }

    }
    private void UploadData(){
         request = new RegisterSecondRequest();
         request.driverMobile = driverPhone;
        if (user_name.getText().length()==0||user_gender.getText().length()==0||user_snNumber.getText().length()==0||
                user_snType.getText().length()==0){
            ToastUtils.show("注册信息不完整",3);
            return;
        }
        else {
            request.nickname = user_name.getText().toString();
            if (user_gender.getText().toString().equals("男")){
                 request.gender ="1";
            }
            else {
                request.gender ="2";
            }
            if (user_snType.getText().toString().equals("身份证")){
                request.type = "1";
                request.ssn = user_snNumber.getText().toString();
            }
            else {
                request.type = "2";
                request.passport = user_snNumber.getText().toString();
            }
            String reqStr = RestClient.getGson().toJson(request);
            TypedString string = new TypedString(reqStr);
            TypedFile positive = new TypedFile("positive",positiveimgSace());
            TypedFile reverse = new TypedFile("reverse",reverseimgSace());

            RestClient.getRestService().registerSecond(string, positive, reverse, new Callback<RegisterSecondBackBean>() {
                @Override
                public void success(RegisterSecondBackBean registerSecondBackBean, Response response) {
                   if (registerSecondBackBean.getErrorCode().equals("0")){
                       ToastUtils.show("注册成功，进入绑车页面",3);
                       SpUtils.putString("AccoundID",registerSecondBackBean.getData(), BaseApplication.getContext());
                       RegisterThirdActivity.RegisterThirdIntent(RegisterSecondActivity.this,2);
                   }
                }
                @Override
                public void failure(RetrofitError error) {
                   ToastUtils.show("注册失败,确认注册信息填写完整",3);
                    Log.e("sss",error.toString());
                }
            });



        }
    }
    private void showPopWindow(final int type){
        final PopupWindow popupWindow = new PopupWindow(this);
        View view = LayoutInflater.from(this).inflate(R.layout.item_popwindows,null);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);//item是否相应点击事件
        popupWindow.setOutsideTouchable(true);
        popupWindow.setContentView(view);
        popupWindow.showAtLocation(allBg_img, Gravity.BOTTOM,0,0);
        popupWindow.update();
        Button btCam = (Button) view.findViewById(R.id.item_popupwindows_camera);
        Button btPhoto = (Button) view.findViewById(R.id.item_popupwindows_Photo);
        Button btCancle = (Button) view.findViewById(R.id.item_popupwindows_cancel);
        btCam.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               //进入相机
               clickTakePhoto(type);
               popupWindow.dismiss();
           }
       });
        btPhoto.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //进入相册
                clickPickFromGallery(type);
                popupWindow.dismiss();
            }
        });
        btCancle.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    /**
     * 进入相机
     * @param type
     */
    private void clickTakePhoto(final int type){
        /**Permission check only required if saving pictures to root of sdcard*/
        int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permissionCheck  == PackageManager.PERMISSION_GRANTED){
            EasyImage.openCamera(this,type);
            getIntent().putExtra(ConstantValues.BUNDLE_APP_STATE, AppState.IN_CAMERA_PHOTO.name());
        }
        else {
            Nammu.askForPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE, new PermissionCallback() {
                @Override
                public void permissionGranted() {
                    EasyImage.openCamera(RegisterSecondActivity.this,type);
                    //
                    getIntent().putExtra(ConstantValues.BUNDLE_APP_STATE, AppState.IN_CAMERA_PHOTO.name());
                }

                @Override
                public void permissionRefused() {

                }
            });
        }
    }

    /**
     *
     * @param requestCode
     * @param resultCode
     * @param data         */

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
            @Override
            public void onImagePicked(File file, EasyImage.ImageSource imageSource, int i) {
                isAccountChanged = true;
                imageUri = Uri.fromFile(file);
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                /**
                 * 这段代码将图片的大小进行缩小
                 */
                BitmapFactory.decodeFile(file.toString(), options);
                // options.inSampleSize = calculateInSampleSize(options, 94, 94);
                final int height = options.outHeight;
                final int width = options.outWidth;
                options.inSampleSize = 1;
                int w = 320;
                int h = 480;
                h = w * height / width;//计算出宽高等比率
                int a = options.outWidth / w;
                int b = options.outHeight / h;
                options.inSampleSize = Math.max(a, b);
                options.inJustDecodeBounds = false;
                bitmap = BitmapFactory.decodeFile(file.toString(), options);
                if (i == 0) {
                    vehicle_head.setImageBitmap(bitmap);
                    vehicle_head.setTag(file.getAbsolutePath());
                    LogUtils.d("new",file.getAbsolutePath());
                } else if (i == 1) {
                    vehicle_end.setImageBitmap(bitmap);
                    vehicle_end.setTag(file.getAbsolutePath());
                    LogUtils.d("new2",file.getAbsolutePath());
                }


            }


            @Override
            public void onImagePickerError(Exception e, EasyImage.ImageSource source, int type) {
                super.onImagePickerError(e, source, type);
            }

            @Override
            public void onCanceled(EasyImage.ImageSource source, int type) {
                super.onCanceled(source, type);
                if (source == EasyImage.ImageSource.CAMERA) {
                    File photoFile = EasyImage.lastlyTakenButCanceledPhoto(RegisterSecondActivity.this);
                    if (photoFile != null) photoFile.delete();
                }
            }
        });
    }
    protected void clickPickFromGallery(int type) {
        /** Some devices such as Samsungs which have their own gallery app require write permission. Testing is advised! */
        getIntent().putExtra(ConstantValues.BUNDLE_APP_STATE, AppState.IN_CAMERA_PHOTO.name());
        EasyImage.openGallery(this,type);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bitmap!=null){
            bitmap.recycle();
        }
        ActivityCollector.removeActivity(this);
        System.gc();
    }

    //获取图片文件
    private  File  positiveimgSace(){
        String HEAD_IMG = "vehicle_head_img";
        headfile = BitmapUtils.saveBmpFile(((BitmapDrawable) vehicle_head.getDrawable()).getBitmap(), HEAD_IMG);
        return headfile;
    }
    //获取图片文件
    private  File  reverseimgSace(){
       String END_IMG = "vehicle_end_img";
     //   if (vehicle_end.getB)
        endfile = BitmapUtils.saveBmpFile(((BitmapDrawable)vehicle_end.getDrawable()).getBitmap(),END_IMG);
        return endfile;
    }
public static void RegisterSecondIntent(Context context,String driverNumber){
    driverPhone = driverNumber;
    Intent intent = new Intent(context,RegisterSecondActivity.class);
    context.startActivity(intent);
}
    private void showTypePop(View view){
        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.type_menu,null);
        typePop = new PopupWindow(linearLayout,150, LinearLayout.LayoutParams.WRAP_CONTENT);
        typePop.setFocusable(false);
        typePop.setOutsideTouchable(true);
        typePop.setBackgroundDrawable(new BitmapDrawable());
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        typePop.showAtLocation(view, Gravity.NO_GRAVITY, location[0]-typePop.getWidth(), location[1]+25);
        final TextView ssn = (TextView) linearLayout.findViewById(R.id.driver_ssn);
        ssn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                user_snType.setText(ssn.getText().toString());
                typePop.dismiss();
                isShowPop = true;
            }
        });
        final TextView passport = (TextView) linearLayout.findViewById(R.id.driver_pass);
        passport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                user_snType .setText(passport.getText().toString());
                typePop.dismiss();
                isShowPop = true;
            }
        });
    }
    private void showPop(View v){
        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.pop_menu,null);
        popupWindow = new PopupWindow(linearLayout,150, LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(false);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        int[] location = new int[2];
        v.getLocationOnScreen(location);
        popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0]-popupWindow.getWidth(), location[1]+25);
        final TextView textMan = (TextView) linearLayout.findViewById(R.id.man);
        textMan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                user_gender.setText(textMan.getText().toString());
                popupWindow.dismiss();
                isShowPop = true;
            }
        });
        final TextView textWoman = (TextView) linearLayout.findViewById(R.id.woman);
        textWoman.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                user_gender.setText(textWoman.getText().toString());
                popupWindow.dismiss();
                isShowPop = true;
            }
        });

    }
}
